package pl.org.lutra.planner.gui.main;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Observer;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;

import pl.org.lutra.planner.Planner;
import pl.org.lutra.planner.gui.resources.Text;
import pl.org.lutra.planner.gui.table.DiveTable;
import pl.org.lutra.planner.gui.util.GuiUtil;
import pl.org.lutra.planner.model.ModelObserverEvent;
import pl.org.lutra.planner.model.input.ChangedObservable;
import pl.org.lutra.planner.model.input.Input;

public class InputPanel extends JPanel {
    private static final long serialVersionUID = 1L;
    
    private ChangedObservable observable = new ChangedObservable();
    private Input input = Planner.getInstance().getInput();
    
    private DiveTable diveTable = new DiveTable();
    
    public InputPanel() {
        super(new BorderLayout());
        
        addObserver(input);
        
        init();
    }
    
    private void addObserver(Observer observer) {
        observable.addObserver(observer);
    }
    
    private void init() {
        GuiUtil.setTitleBorderWithPadding(this, "dive.profile");
        
        InputMap inputMap = diveTable.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = diveTable.getActionMap();
        
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "deleteRow");
        actionMap.put("deleteRow", new AbstractAction() {
            private static final long serialVersionUID = -5755156936991290500L;
            
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteDiveSegment();
            }
        });
        
        JScrollPane scroll = new JScrollPane(diveTable);
        scroll.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                addDiveSegment();
            }
        });
        
        String tableHelpMessage = GuiUtil.prepareMultiLineToolTip(Text.get("dive.table.toolTip"));
        diveTable.setToolTipText(tableHelpMessage);
        scroll.setToolTipText(tableHelpMessage);
        
        add(scroll, BorderLayout.CENTER);
    }
    
    public void addDiveSegment() {
        diveTable.getModel().addRow();
        observable.notifyObservers(ModelObserverEvent.INPUT_CHANGED);
    }
    
    public void deleteDiveSegment() {
        diveTable.getModel().deleteRow(diveTable.getSelectedRow());
        observable.notifyObservers(ModelObserverEvent.INPUT_CHANGED);
    }
    
}
